package sc.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;


/** 
* CrashHandler.java: UncaughtException运行异常捕获，并记录至文件中 
* CatchException(Context context); 
* ----- 2019-12-13 下午1:40:10 scimence */
public class CrashHandler implements UncaughtExceptionHandler
{
	/** 调用一次此函数，即可捕获运行异常 */
	public static void CatchException(Context context)
	{
		INSTANCE.init(context.getApplicationContext());
	}
	
	// -----------------------------
	
	private static final String TAG = "CrashHandler";
	String crashPath = "/sdcard/ltsdk/crash/";							// 异常信息保存路径（可自定义）
	
	private UncaughtExceptionHandler mDefaultHandler;
	private static CrashHandler INSTANCE = new CrashHandler();
	private Context mContext;
	private Map<String, String> infos = new HashMap<String, String>();	// 运行异常相关信息
	
	/** 保证只有一个CrashHandler实例 */
	private CrashHandler()
	{}
	
	/** 初始化 context */
	private void init(Context context)
	{
		if(context != null && mContext == null)
		{
			mContext = context;
			mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();	// 获取系统默认的UncaughtException处理器
			Thread.setDefaultUncaughtExceptionHandler(this);				// 设置该CrashHandler为程序的默认处理器
		}
	}
	
	/** 当UncaughtException发生时会转入该函数来处理 */
	@Override
	public void uncaughtException(Thread thread, Throwable ex)
	{
		String exStr = ToString(ex);
		Log.e(TAG, "游戏异常 : " + exStr);
		
		if (!handleException(ex) && mDefaultHandler != null)
		{
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		}
		else
		{
			Log.e(TAG, "待处理游戏异常！ ");
			
			try
			{
				Thread.sleep(3000);
			}
			catch (InterruptedException e)
			{
				Log.e(TAG, "error : ", e);
			}
			
			// 退出程序
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(1);
		}
	}
	
	/** 处理运行异常，Toast提示，并保存异常信息至文件中 */
	private boolean handleException(Throwable ex)
	{
		if (ex == null) { return false; }
		
		// 使用Toast来显示异常信息
		new Thread()
		{
			@Override
			public void run()
			{
				Looper.prepare();
				Toast.makeText(mContext, "很抱歉，程序出现运行异常。" + "\r\n\r\n" + "异常log信息，已保存至目录:\r\n" + crashPath, Toast.LENGTH_LONG).show();
				Looper.loop();
			}
		}.start();
		
		Log.e(TAG, " handleException() -> 处理异常信息： \r\n" + ex.toString());
		
		infos.clear();					// 清空记录的异常信息
		collectDeviceInfo(mContext);	// 收集设备参数信息
		saveCrashInfo2File(ex);			// 保存运行异常相关信息至文件
		return true;
	}
	
	/** 获取设备参数信息 */
	public void collectDeviceInfo(Context ctx)
	{
		try
		{
			PackageManager pm = ctx.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
			if (pi != null)
			{
				String versionName = pi.versionName == null ? "null" : pi.versionName;
				String versionCode = pi.versionCode + "";
				infos.put("versionName", versionName);
				infos.put("versionCode", versionCode);
			}
		}
		catch (NameNotFoundException e)
		{
			Log.e(TAG, "an error occured when collect package info", e);
		}
		
		Field[] fields = Build.class.getDeclaredFields();
		for (Field field : fields)
		{
			try
			{
				field.setAccessible(true);
				infos.put(field.getName(), field.get(null).toString());
				Log.d(TAG, field.getName() + " : " + field.get(null));
			}
			catch (Exception e)
			{
				Log.e(TAG, "获取设备信息出错...", e);
			}
		}
	}
	
	/** 获取异常文本信息 */
	private String ToString(Throwable ex)
	{
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry : infos.entrySet())
		{
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key + "=" + value + "\r\n");
		}
		
		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null)
		{
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		printWriter.close();
		String result = writer.toString();
		
		return result;
	}
	
	/** 保存运行异常信息到文件 */
	private String saveCrashInfo2File(Throwable ex)
	{
		
		StringBuffer sb = new StringBuffer();
		
		// 输出设备信息
		sb.append("----------------------" + "\r\n");
		sb.append("设备信息：" + "\r\n\r\n");
		
		for (Map.Entry<String, String> entry : infos.entrySet())
		{
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key + "=" + value + "\r\n");
		}
		
		
		// 输出运行异常信息
		sb.append("----------------------" + "\r\n");
		sb.append("运行异常信息：" + "\r\n\r\n");
		
		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null)
		{
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		printWriter.close();
		String result = writer.toString();
		sb.append(result);
		
		try
		{
			DateFormat formatter = new SimpleDateFormat("yyyyMMdd_HH.mm.ss");	// 格式化日期
			String time = formatter.format(new Date());
			String timestamp = (System.currentTimeMillis() + "").substring(0, 4);
			String fileName = "crash_" + time + "_" + timestamp + ".txt";
			
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			{
				File dir = new File(crashPath);
				if (!dir.exists())
				{
					dir.mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(crashPath + fileName);
				fos.write(sb.toString().getBytes());
				fos.close();
			}
			return fileName;
		}
		catch (Exception e)
		{
			Log.e(TAG, "异常信息，输出至文件出错...", e);
		}
		return null;
	}
}